package cn.itcast.service.impl;

import cn.itcast.dao.CourierRepository;
import cn.itcast.domain.base.Courier;
import cn.itcast.service.CourierService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;
import java.util.Set;

@Service
public class CourierServiceImpl implements CourierService {
    @Autowired
    private CourierRepository courierRepository;
    @Override
    @Transactional
    @RequiresPermissions("courier:add")//细粒度权限控制 指定该方法所需要权限
    //权限不足时,代理对象无法跳转到权限不足页面,而是抛出一个异常
    public void save(Courier courier) {
        courierRepository.save(courier);
    }

    @Override
    public Page<Courier> findAll(Specification<Courier> specification, Pageable pageable) {
        return courierRepository.findAll(specification,pageable);
    }

    @Override
    public void delBatch(String[] idArray) {
        for(String idStr:idArray){
            Integer id =Integer.parseInt(idStr);
            courierRepository.updateDelTag(id);
        }
    }

    @Override
    public void solBatch(String[] idArray) {
        for(String idstr:idArray){
            Integer id =Integer.parseInt(idstr);
            courierRepository.solBatch(id);
        }
    }

    @Override
    public List<Courier> findNoassociation() {
        Specification<Courier>specification=new Specification<Courier>() {
            @Override
            public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                return cb.isEmpty(root.get("fixedAreas").as(Set.class));
            }
        };
        return courierRepository.findAll(specification);
    }
}
